from collections import defaultdict
from copy import copy

import xlrd

wb = xlrd.open_workbook(
    'E:/群晖备份/SynologyDrive/kpmg/长沙银行/2021行政区划-民政部.xls')


def isEmpty(str):
    if str is None or str == '' or str == '\r' or str == '\n' or str == '\r\n':
        return True
    return False


def format_not_number(val):
    return str(val).replace('.0', '')


def get_mapping(sheet):
    mapping = defaultdict(str)
    for row in range(2, sheet.nrows):
        data_cols = sheet.row_values(row, start_colx=1, end_colx=3)
        key = format_not_number(data_cols[0]).strip()
        value = data_cols[1].strip()
        mapping[key] = value
    return mapping


if __name__ == '__main__':
    sheet = wb.sheet_by_index(0)
    # data_rows = sheet.col_values(1, 2)
    # print(data_rows)
    mapping = get_mapping(sheet)
    # mapping_copy = copy(mapping)

    result_mapping = defaultdict(str)

    for key_, value in mapping.items():
        # if (key_ == '130102'):
            # print(1)
        if not isEmpty(key_):
            name = ''
            curent_key = str(key_)
            parent_key = curent_key[0: 4]
            parent_key = parent_key + '00'
            parent_name = result_mapping[parent_key]
            if isEmpty(parent_name):
                parent_key = curent_key[0: 2]
                parent_key = parent_key + '0000'
                parent_name = result_mapping[parent_key]
                if isEmpty(parent_name):
                    # raise Exception(curent_key + '没有找到上级')
                    name = value
                else:
                    name = parent_name + value
            else:
                name = parent_name + value
            result_mapping[key_] = name
    for key_, value in result_mapping.items():
        if not isEmpty(value):
            print(value)
